import {Layout} from "element-plus"

type ScrollElement=HTMLDivElement | null;

interface ScrollReturn{
    contentRef:Ref<Layout | null>;
    scrollRef:Ref<ScrollElement>;
    scrollToTop:()=>Promise<void>;
    scrollToBottom:()=>Promise<void>;
    scrollToBottomIfAtBottom:()=>Promise<void>;
 }


export function useScroll():ScrollReturn{
    const contentRef = ref<Layout | null>(null);
    const scrollRef = ref<ScrollElement>(null);

    async function scrollToTop():Promise<Void>{
        await nextTick();
        try{
           if(contentRef.value && scrollRef.value){
               contentRef.value.scrollTo({top:0});
           }
        }catch(error){
            console.error(error);
        }
    }

    async function scrollToBottom():Promise<Void>{
        await nextTick();
        try{
            if(contentRef.value && scrollRef.value){
                contentRef.value.scrollTo({top:scrollRef.value.scrollHeight,behavior:'smooth'});
            }
        }catch(error){
            console.error(error);
        }
    }
    async function scrollToBottomIfAtBottom():Promise<Void>{
        await nextTick();
        try{
            if(contentRef.value && scrollRef.value){
                const threshold = 100;
                const distance=scrollRef.value.scrollHeight - scrollRef.value.clientHeight - scrollRef.value.scrollTop;
                if (distance <= threshold) {
                   contentRef.value.scrollTo({top:scrollRef.value.scrollHeight});
                }
            }
        }catch(error){
            console.error(error);
        }
    }
    return {
        contentRef,
        scrollRef,
        scrollToTop,
        scrollToBottom,
        scrollToBottomIfAtBottom
    }
}